#include <QApplication>
#include <QSettings>
#include <QFile>
#include <QIODevice>

#include "cvsettings.h"

CVSettings *CVSettings::instance = NULL;
CVSettings::CVSettings()
{
    init();
}

CVSettings::~CVSettings()
{
    delete instance;
    delete accounts;
}

CVSettings *CVSettings::get()
{
    if (!instance) {
        instance = new CVSettings();
    }

    return instance;
}

void CVSettings::init()
{
    accounts = new QList<Account *>();

    readSettings();
}

QString CVSettings::getFileName()
{
    QString appPath = QApplication::applicationDirPath();
    QString appName = QApplication::applicationName();
    if (appName.isEmpty())
    {
        appName = "qtcv";
    }
    return appPath + "/." + appName;
}

void CVSettings::readSettings()
{
    QString fileName = getFileName();
    QFile fileRead(fileName);
    if (fileRead.exists())
    {
        bool result = fileRead.open(QIODevice::ReadOnly);
        if (result)
        {
            Account *account = new Account();
            CVSetting *setting = new CVSetting();
            QDataStream readDataStream(&fileRead);
            readDataStream >> setting->m_network >> setting->m_userId >> setting->m_password;
            account->setNetwork(setting->m_network);
            account->setUserId(setting->m_userId);
            account->setPassword(setting->m_password);
            accounts->append(account);
            delete setting;
        }
    }
    fileRead.close();
}

void CVSettings::writeFile()
{
    QString fileName = getFileName();
    QFile fileWrite(fileName);
    fileWrite.open(QIODevice::WriteOnly);
    QDataStream writeDataStream(&fileWrite);

    int size = accounts->size();
    if (size > 0)
    {
        for(int i = 0; i < size; ++i)
        {
            Account *account = accounts->at(i);
            CVSetting *setting = new CVSetting();
            setting->m_network = account->getNetwork();
            setting->m_userId = account->getUserId();
            setting->m_password = account->getPassword();
            writeDataStream << setting->m_network << setting->m_userId << setting->m_password;
            delete setting;
        }
        fileWrite.close();
    }
}

void CVSettings::addAccount(const QString &network, const QString &email, const QString &password)
{
    if (!network.isEmpty() && !email.isEmpty())
    {
        Account *account = new Account(network, email, password);
        accounts->append(account);

        writeFile();
    }
}

void CVSettings::addAccount(Account *account)
{
    accounts->append(account);
}

QList<Account *> *CVSettings::getAccounts()
{
    return accounts;
}

